package com.lora.web;

import com.lora.enums.EquipmentEnum;
import com.lora.service.EquipmentService;
import com.lora.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/camera")
public class CameraController {
    @Autowired
    EquipmentService equipmentService;
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @GetMapping("/getCamera")
    public Object getCamera(){
        List<Map<String, Object>> service = jdbcTemplate.queryForList("select eid from equipent where type = 14");
        if(service==null||service.size()==0){
            return null;
        }
        List<Map<String, Object>> query = jdbcTemplate.queryForList("select eid from equipent where type = 13");
        List<String> rstp=new ArrayList<String>();
        if(query!=null&&query.size()>0){
            for (Map<String, Object> stringObjectMap : query) {
                Object eid = stringObjectMap.get("eid");
                if (eid!=null){
                    rstp.add("http://"+service.get(0).get("eid")+":9815/hls/"+eid.toString().substring(eid.toString().lastIndexOf(".")+1)+".m3u8");
                }
            }
            return rstp;
        }
        return null;
    }



    @GetMapping("/chenckCamera")
    public boolean chenckCamera(HttpServletRequest request){
        return isPortUsing(getIp(request),7600);
    }

    @GetMapping("/downloadFile")
    public static void downloadFile(HttpServletResponse response){
        //设置文件路径
        File file = new File(StringUtil.filepath()+"camera"+File.separator+"Streamedia.exe");
        if (file.exists()) {
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            try {
                response.setHeader("Content-Disposition", "attachment;filename="+new String("Streamedia.exe".getBytes("utf-8"),"ISO-8859-1"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            byte[] buffer = new byte[4096];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public static String getIp(HttpServletRequest request) {
        String ip = null;
        ip = request.getHeader("x-forwarded-for");
        if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
            ip = request.getRemoteAddr();
            if (ip.equals("127.0.0.1")) {
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ip = inet.getHostAddress();
            }
        }
        if ((ip != null) && (ip.length() > 15)) {
            if (ip.indexOf(",") > 0) {
                ip = ip.substring(0, ip.indexOf(","));
            }
        }
        return ip;
    }

    /***
     * 测试主机Host的port端口是否被使用
     * @param host
     * @param port
     * @throws UnknownHostException
     */
    public static boolean isPortUsing(String host,int port){
        boolean flag = false;
        try {
            InetAddress Address = InetAddress.getByName(host);
            Socket socket = new Socket(Address, port);  //建立一个Socket连接
            flag = true;
        }catch (Exception e){

        }
        return flag;
    }
}
